package com.henry.chatkit.weight.gatherimage

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.SparseArray
import android.widget.ImageView


@SuppressLint("AppCompatCustomView")
open class ShadeImageView : ImageView {

    private val sRoundBitmapArray = SparseArray<Bitmap>()
    private val mShadePaint = Paint()
    private var mRoundBitmap: Bitmap? = null
    private var radius: Int = 5

    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        init()
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        init()
    }

    private fun init() {
        setLayerType(LAYER_TYPE_HARDWARE, null)
    }

    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        mShadePaint.color = Color.RED
        mShadePaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN)
        mRoundBitmap = sRoundBitmapArray.get(measuredWidth + radius)
        if (mRoundBitmap == null) {
            mRoundBitmap = getRoundBitmap()
            sRoundBitmapArray.put(measuredWidth + radius, mRoundBitmap)
        }
        mRoundBitmap?.let { canvas?.drawBitmap(it, 0F, 0F, mShadePaint) }
    }

    private fun getRoundBitmap(): Bitmap? {
        val output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(output)
        val color = Color.parseColor("#cfd3d8")
        val rect = Rect(0, 0, measuredWidth, measuredHeight)
        val rectF = RectF(rect)
        val paint = Paint()
        paint.isAntiAlias = true
        canvas.drawARGB(0, 0, 0, 0)
        paint.color = color
        canvas.drawRoundRect(rectF, radius.toFloat(), radius.toFloat(), paint)
        return output
    }

    fun getRadius(): Int {
        return radius
    }

    fun setRadius(radius: Int) {
        this.radius = radius
    }
}